<template>
  <div class="table_wrap">
    <!-- 操作栏 -->
    <el-card style="margin-bottom: 6px; padding: 0px">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="75px"
        style="margin-bottom: -20px"
      >
        <el-form-item label="项目类别" prop="projectType">
          <el-input
            v-model="queryParams.projectType"
            placeholder="请输入项目类别"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="departmentName">
          <el-input
            v-model="queryParams.departmentName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="创建人" prop="username">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入创建人"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="timeValue">
          <!-- <el-date-picker
            v-model="timeValue"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
          >
          </el-date-picker> -->
          <el-date-picker
            v-model="queryParams.startTime"
            type="date"
            placeholder="选择开始时间"
            size="small"
            :editable="false"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="timeValue">
          <!-- <el-date-picker
            v-model="timeValue"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
          >
          </el-date-picker> -->
          <el-date-picker
            v-model="queryParams.endTime"
            type="date"
            placeholder="选择结束时间"
            size="small"
            :editable="false"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-arrow-right"
            size="mini"
            @click="toWorkTime"
            >工时编码</el-button
          >
        </el-form-item>
        <el-form-item style="float: right">
          <el-upload
            ref="importUploadRef"
            :auto-upload="false"
            accept=".xls,.xlsx"
            :limit="1"
            action="none"
            :show-file-list="false"
            :on-change="importData"
            style="margin-right: 0.75rem; display: inline-block"
          >
            <el-button
              type="warning"
              plain
              icon="el-icon-upload2"
              size="mini"
              v-loading.fullscreen.lock="fullscreenLoading"
              >文件导入</el-button
            >
          </el-upload>

          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="openExportDialog('itemStatic')"
            >工时明细导出</el-button
          >
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="openExportDialog('projectStatic')"
            >项目工时明细导出</el-button
          >
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="openAddDialog"
            >新增</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 表格数据 -->
    <div class="table_wrap__table">
      <el-table
        :data="tableData"
        style="width: 100%; min-height: 70vh"
        border
        v-loading="loading"
        :row-class-name="tableRowClassName"
      >
        <el-table-column label="序号" prop="id" />
        <el-table-column label="创建人" prop="username" />
        <el-table-column label="项目类别" prop="projectType" />
        <el-table-column label="项目名称" prop="projectName" />
        <!-- <el-table-column label="是否合并" prop="isFinal" />
        <el-table-column label="合并数据" prop="type" /> -->
        <el-table-column label="部门名称" prop="departmentName" />

        <el-table-column label="工作内容" prop="content" />

        <el-table-column label="困难及协调事项" prop="others" />

        <el-table-column label="工时" prop="workTime" />
        <el-table-column label="开始时间" prop="startTime" />
        <el-table-column label="结束时间" prop="endTime" />
        <el-table-column align="right" label="操作">
          <template #default="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              type="text"
              @click="openEdit(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="table_wrap__table__pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="queryParams.pageNum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="queryParams.pageSize"
          layout="sizes, prev, pager, next"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 新增编辑框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      :destroy-on-close="true"
      @close="handleDialogClose"
      top="5vh"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
          label="创建人"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input
            v-model="form.username"
            size="small"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="项目类别"
          :label-width="formLabelWidth"
          prop="projectType"
        >
          <el-input
            v-model="form.projectType"
            size="small"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="项目名称"
          :label-width="formLabelWidth"
          prop="projectName"
        >
          <el-input
            v-model="form.projectName"
            size="small"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="部门名称"
          :label-width="formLabelWidth"
          prop="departmentName"
        >
          <el-input
            v-model="form.departmentName"
            size="small"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="工作内容"
          :label-width="formLabelWidth"
          prop="content"
        >
          <el-input
            type="textarea"
            v-model="form.content"
            size="small"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="困难及协调事项"
          :label-width="formLabelWidth"
          prop="others"
        >
          <el-input
            type="textarea"
            v-model="form.others"
            size="small"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="工时"
          :label-width="formLabelWidth"
          prop="workTime"
        >
          <el-input-number
            v-model="form.workTime"
            controls-position="right"
            :min="0"
            :max="100"
            size="small"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="开始时间"
          :label-width="formLabelWidth"
          prop="startTime"
        >
          <el-date-picker
            v-model="form.startTime"
            type="date"
            placeholder="选择开始时间"
            size="small"
            :editable="false"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="结束时间"
          :label-width="formLabelWidth"
          prop="endTime"
        >
          <el-date-picker
            v-model="form.endTime"
            type="date"
            placeholder="选择结束时间"
            size="small"
            :editable="false"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleComfirm('form')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 导出框 -->
    <el-dialog
      :title="exportDialogTitle"
      :visible.sync="exportDialogFormVisible"
      :destroy-on-close="true"
      @close="handleExportDialogClose"
      top="30vh"
    >
      <el-form :model="exportFrom">
        <el-form-item label="开始时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="exportFrom.startTime"
            type="date"
            placeholder="选择开始时间"
            size="small"
            :editable="false"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="exportFrom.endTime"
            type="date"
            placeholder="选择结束时间"
            size="small"
            :editable="false"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleExport">导 出</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTableData,
  deleteTableInfo,
  insertTableInfo,
  updateTableInfo,
  exportItemStatic,
  exportDetail,
  uploadExcel
} from '@/api/home'
import downloadFile from '@/utils/common.js'
export default {
  name: 'HomeView',
  data () {
    return {
      tableData: [], // 表格数据
      loading: true, // 加载动画
      //查询数据
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectType: null,
        projectName: null,
        departmentName: null,
        username: null,
        startTime: null,
        endTime: null
      },
      dialogFormVisible: false, // 弹窗显示
      exportDialogFormVisible: false,
      // 表单数据
      form: {
        id: '',
        projectType: '',
        projectName: '',
        departmentName: '',
        content: '',
        others: '',
        username: '',
        workTime: '',
        startTime: '',
        endTime: ''
      },
      formLabelWidth: '120px', // 表单标题
      dialogTitle: '新增', // 新增,编辑
      dialogType: '', // add,edit
      exportType: '', //
      total: null,
      // 表单验证规则
      rules: {
        projectType: [
          { required: true, message: '请输入项目类别', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入工作内容', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入创建人', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ]
      },
      exportFrom: {
        startTime: null,
        endTime: null
      },
      exportDialogTitle: '',
      fullscreenLoading: false // 全屏加载
    }
  },
  created () {
    // 获取表格数据
    this.getTableInfo()
  },
  methods: {
    /**
     * @functionName getTableInfo
     * @param {类型} 参数无
     * @description 获取表格数据
     * @author 蒋友为
     * @date 2024-05-23 22:48:31
     * @version V1.0.0
     * @return
     */
    getTableInfo () {
      this.loading = true // 加载动画
      const params = {
        ...this.queryParams,
        projectType: this.queryParams.projectType || null,
        projectName: this.queryParams.projectName || null,
        departmentName: this.queryParams.departmentName || null,
        username: this.queryParams.username || null,
        startTime: this.queryParams.startTime || null,
        endTime: this.queryParams.endTime || null
      }
      // console.log(params)
      getTableData(params).then(res => {
        if (res.status === 200) {
          // console.log(res)
          this.total = res.data.size
          this.tableData = res.data.data
          this.loading = false
        }
      })
    },

    /**
     * @functionName handleComfirm
     * @param {类型} 参数
     * @description 确认提交数据
     * @author 蒋友为
     * @date 2024-05-25 14:41:49
     * @version V1.0.0
     * @return
     */
    handleComfirm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = {}
          if (this.dialogType === 'add') {
            const { id, ...rest } = this.form
            data = {
              ...rest
            }
            insertTableInfo(data)
              .then(res => {
                // console.log(res)
                if (res.status === 200) {
                  this.$message.success('新增成功')
                  this.dialogFormVisible = false
                  this.getTableInfo()
                }
                data = {}
              })
              .catch(err => {
                this.$message.error('请检查输入信息是否正确')
              })
          } else if (this.dialogType === 'edit') {
            data = { ...this.form }
            updateTableInfo(data)
              .then(res => {
                // console.log(res)
                data = {}
                if (res.status === 200) {
                  this.$message.success('编辑成功')
                  this.dialogFormVisible = false
                  this.getTableInfo()
                }
              })
              .catch(err => {
                this.$message.error('请检查输入信息是否正确')
              })
          }
          // console.log(data)
        } else {
          return false
        }
      })
    },

    /**
     * @functionName handleDelete
     * @param {类型} 参数
     * @description 删除单条数据
     * @author 蒋友为
     * @date 2024-05-25 15:47:56
     * @version V1.0.0
     * @return
     */
    handleDelete (index, item) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const data = {
            id: item.id
          }
          deleteTableInfo(data)
            .then(res => {
              // console.log(res)
              if (res.status === 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.getTableInfo()
              } else {
                this.$message({
                  type: 'error',
                  message: '删除失败!'
                })
              }
            })
            .catch(err => {
              // console.log(err)
              this.$message({
                type: 'error',
                message: '删除失败'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    /**
     * @functionName handleQuery
     * @param {类型} 参数
     * @description 查询数据
     * @author 蒋友为
     * @date 2024-05-25 14:41:27
     * @version V1.0.0
     * @return
     */
    handleQuery () {
      // console.log(this.queryParams)
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getTableInfo()
    },

    /**
     * @functionName resetQuery
     * @param {类型} 参数
     * @description 重置查询条件
     * @author 蒋友为
     * @date 2024-05-25 14:37:10
     * @version V1.0.0
     * @return
     */
    resetQuery () {
      const { pageNum, pageSize, ...rest } = this.queryParams
      Object.keys({ ...rest }).forEach(key => {
        if (this.queryParams[key] === null || this.queryParams[key] === '') {
          return
        }
        this.queryParams[key] = null
        this.getTableInfo()
      })
    },

    /**
     * @functionName importData
     * @param {类型} 参数
     * @description excel文件导入
     * @author 蒋友为
     * @date 2024-05-25 16:13:16
     * @version V1.0.0
     * @return
     */
    importData (file) {
      if (!file) {
        return false
      } else if (!/.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        this.$message.error('上传格式不正确,请上传xls或者xlsx格式')
        this.$refs.importUploadRef.clearFiles()
        return false
      }
      let formData = new FormData()
      formData.append('file', file.raw)
      this.$refs.importUploadRef.clearFiles()
      // console.log(file.raw)
      this.fullscreenLoading = true
      uploadExcel(formData)
        .then(res => {
          // console.log(res)
          if (res.status === 200) {
            this.$message.success('导入成功')
            this.getTableInfo()
            this.fullscreenLoading = false
          } else {
            this.$message.error('导入失败')
          }
        })
        .catch(err => {
          this.$message.error('导入失败')
        })
    },

    /**
     * @functionName exportTableData
     * @param {类型} 参数
     * @description 工时明细导出
     * @author 蒋友为
     * @date 2024-05-25 16:13:43
     * @version V1.0.0
     * @return
     */
    exportTableData (data) {
      exportDetail(data)
        .then(res => {
          if (res.status === 200) {
            // console.log(res)
            this.$message.success('导出成功')
            downloadFile(res.data, '工时明细')
            this.exportDialogFormVisible = false
          } else {
            this.$message.error('导出失败')
            this.exportDialogFormVisible = false
          }
        })
        .catch(err => {
          // console.log(err)
          this.$message.error('导出失败')
          this.exportDialogFormVisible = false
        })
    },

    /**
     * @functionName exportStatic
     * @param {类型} 参数
     * @description 项目工时明细导出
     * @author 蒋友为
     * @date 2024-05-25 16:13:56
     * @version V1.0.0
     * @return
     */
    exportStatic (data) {
      exportItemStatic(data)
        .then(res => {
          if (res.status === 200) {
            this.$message.success('导出成功')
            downloadFile(res.data, '项目工时明细')
            this.exportDialogFormVisible = false
          } else {
            this.$message.error('导出失败')
            this.exportDialogFormVisible = false
          }
        })
        .catch(err => {
          // console.log(err)
          this.$message.error('导出失败')
          this.exportDialogFormVisible = false
        })
    },

    /**
     * @functionName openExportDialog
     * @param {类型} 参数
     * @description 导出弹窗
     * @author 蒋友为
     * @date 2024-05-26 18:24:15
     * @version V1.0.0
     * @return
     */
    openExportDialog (type) {
      this.exportDialogFormVisible = true
      if (type === 'itemStatic') {
        this.exportDialogTitle = '工时明细导出'
        this.exportType = 'itemStatic'
      }
      if (type === 'projectStatic') {
        this.exportDialogTitle = '项目工时明细导出'
        this.exportType = 'projectStatic'
      }
    },

    /**
     * @functionName handleExport
     * @param {类型} 参数
     * @description 导出
     * @author 蒋友为
     * @date 2024-05-26 18:24:50
     * @version V1.0.0
     * @return
     */
    handleExport () {
      const data = {
        ...this.exportFrom
      }
      if (this.exportType === 'itemStatic') {
        this.exportTableData(this.exportFrom)
      } else if (this.exportType === 'projectStatic') {
        this.exportStatic(this.exportFrom)
      }
    },

    /**
     * @functionName openAddDialog
     * @param {类型} 参数
     * @description 打开新增框
     * @author 蒋友为
     * @date 2024-05-25 14:32:48
     * @version V1.0.0
     * @return
     */
    openAddDialog () {
      this.dialogFormVisible = true
      this.dialogTitle = '新增'
      this.dialogType = 'add'
    },

    /**
     * @functionName openEdit
     * @param {类型} 参数
     * @description 打开编辑框
     * @author 蒋友为
     * @date 2024-05-25 14:36:08
     * @version V1.0.0
     * @return
     */
    openEdit (index, item) {
      this.dialogFormVisible = true
      this.dialogTitle = '编辑'
      this.dialogType = 'edit'

      const {
        isFinal,
        createTime,
        updateTime,
        userSum,
        pageNum,
        pageSize,
        itemSum,
        type,
        ...rest
      } = item
      this.form = {
        ...rest
      }
    },

    /**
     * @functionName handleDialogClose
     * @param {类型} 参数
     * @description 关闭弹窗清空数据
     * @author 蒋友为
     * @date 2024-05-25 14:35:16
     * @version V1.0.0
     * @return
     */
    handleDialogClose () {
      Object.keys(this.form).forEach(key => {
        this.form[key] = null
      })
    },

    /**
     * @functionName handleExportDialogClose
     * @param {类型} 参数
     * @description 关闭弹窗清空数据
     * @author 蒋好东
     * @date 2024-05-26 18:16:49
     * @version V1.0.0
     * @return
     */
    handleExportDialogClose () {
      Object.keys(this.exportFrom).forEach(key => {
        this.exportFrom[key] = null
      })
    },

    /**
     * @functionName tableRowClassName
     * @param {类型} 参数
     * @description 表格中所有type=0的数据做判断，将工时（workTime）大于8的背景改为红色显示出来
     * @author 蒋友为
     * @date 2024-05-25 17:48:18
     * @version V1.0.0
     * @return
     */
    tableRowClassName ({ row, rowIndex }) {
      // console.log(row)
      if (row.type === '0' && row.workTime > 8) {
        return 'warning-row'
      }
      return ''
    },

    /**
     * @functionName handleSizeChange
     * @param {类型} 参数
     * @description 改变每页条数
     * @author 蒋友为
     * @date 2024-05-25 14:35:16
     * @version V1.0.0
     * @return
     */
    handleSizeChange (val) {
      this.queryParams.pageSize = val
      this.getTableInfo()
    },

    /**
     * @functionName handleCurrentChange
     * @param {类型} 参数
     * @description 改变当前页
     * @author 蒋友为
     * @date 2024-05-25 14:35:45
     * @version V1.0.0
     * @return
     */
    handleCurrentChange (val) {
      this.queryParams.pageNum = val
      this.getTableInfo()
    },

    toWorkTime () {
      this.$router.push({
        path: '/WorkTime'
      })
    }
  }
}
</script>

<style scoped lang="scss">
.table_wrap {
  padding: 20px;
  background-color: #f6f6f6;

  &__table {
    padding: 20px;
    background-color: #fff;
    display: flex;
    flex-direction: column;

    &__pagination {
      margin: 20px 0 0 auto;
    }
  }
}

::v-deep .el-table .warning-row {
  background: #fcdada;
  color: #ef4444;
}
</style>
